import React, { FC, ReactElement, useEffect, useMemo, useState } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import dayjs from 'dayjs';
import type { ColumnProps } from '@douyinfe/semi-ui/lib/es/table';
import { Table, Button, Toast, Popconfirm } from '@douyinfe/semi-ui';
import { KeywordSearch, EllipseRender } from '@/components';
import {
  getFieldsGoodsServicesList,
  deleteFieldsGoodsServicesItem
} from '@/services';

const FieldsGoodsServiceList: FC = (): ReactElement => {
  const routeNavigate = useNavigate();
  const [tableLoading, setTableLoading] = useState<boolean>(false);
  const [keyword, setKeyword] = useState('');
  const [tableData, setTableData] = useState<Array<Record<string, any>>>([]);

  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [total, setTotal] = useState(0);

  const tableColumns: ColumnProps<Record<string, any>>[] = useMemo(() => {
    return [
      {
        dataIndex: 'id',
        title: '服务ID',
        fixed: 'left',
        width: 100,
        // sorter: true,
        render: t => {
          if ([null, undefined, ''].includes(t)) {
            return '-';
          }

          return (
            <Link
              style={{ color: 'var(--semi-color-primary)' }}
              to={`/service/fields-goods-services/detail?id=${t}`}
            >
              {t}
            </Link>
          )
        }
      },
      {
        dataIndex: 'parking',
        title: '停车场',
        width: 200,
        render: t => (<EllipseRender message={t} maxLength={16} />),
      },
      {
        dataIndex: 'wifi',
        title: 'WIFI',
        width: 180,
        render: t => (<EllipseRender message={t} maxLength={16} />),
      },
      {
        dataIndex: 'createTime',
        title: '创建时间',
        width: 200,
        render: (t: string | undefined | null) => {
          if ([null, undefined, ''].includes(t)) {
            return '-';
          }
          return dayjs(t).format('YYYY-MM-DD HH:mm:ss');
        }
      },
      {
        dataIndex: 'updateTime',
        title: '更新时间',
        width: 200,
        render: (t) => {
          if ([null, undefined, ''].includes(t)) {
            return '-';
          }
          return dayjs(t).format('YYYY-MM-DD HH:mm:ss');
        }
      },
      {
        title: '操作',
        dataIndex: 'action',
        width: 300,
        fixed: 'right',
        render: (t, row) => {
          return (
            <div>
              <Button
                style={{ marginRight: 8 }}
                type="primary"
                theme="solid"
                onClick={() => routeNavigate(`/service/fields-goods-services/update?id=${row.id}`)}
              >
                编辑
              </Button>
              <Popconfirm
                title="确认删除该服务吗？"
                position="leftTop"
                trigger="hover"
                okButtonProps={{
                  type: 'danger',
                  theme: 'solid',
                }}
                onConfirm={() => handleConfirmDeleteService(row.id)}
              >
                <Button
                  style={{ marginRight: 8 }}
                  type="danger"
                  theme="solid"
                >
                  删除
                </Button>
              </Popconfirm>
            </div>
          )
        }
      },
    ];
  }, [routeNavigate, handleConfirmDeleteService]);

  function handleKeywordChange(newKeyword: string) {
    setKeyword(newKeyword);
  }

  function handleSearch() {
    setPage(1);
    getList(1, pageSize, keyword);
  }

  function handleTablePaginationChange(page: number, pageSize: number) {
    setPage(page);
    setPageSize(pageSize);
    getList(page, pageSize, keyword);
  }

  const handleCreateBtnClick = () => {
    routeNavigate('/service/fields-goods-services/create');
  };

  async function handleConfirmDeleteService(id: string | number) {
    setTableLoading(true);
    try {
      const { code, message } = await deleteFieldsGoodsServicesItem(id);
      if (code !== 0) {
        throw new Error(message);
      } else {
        Toast.success('删除成功');
        getList(page, pageSize, keyword);
      }
    } catch (e) {
      Toast.error(`删除失败: ${(e instanceof Error) ? e.message : 'Error'}`);
    }
    setTableLoading(false);
  }

  useEffect(() => {
    getList(1, 10, '');
  }, []);

  async function getList(page: number, pageSize: number, keyboard: string = '') {
    setTableLoading(true);
    try {
      const { data } = await getFieldsGoodsServicesList(page, pageSize, keyword);
      const { list, total } = data;
      setTableData(list);
      setTotal(total);
    } catch (e) {
      Toast.error(`获取列表失败: ${(e instanceof Error) ? e.message : 'Error'}`);
    }
    setTableLoading(false);
  }

  return (
    <div className="container-full fields-goods-service-list">
      <KeywordSearch
        placeholder="请输入关键词"
        loading={tableLoading}
        keyword={keyword}
        handleKeywordChange={handleKeywordChange}
        handleSearch={handleSearch}
      >
        <Button
          type="primary"
          theme="solid"
          onClick={handleCreateBtnClick}
        >
          新建条目
        </Button>
      </KeywordSearch>
      <Table
        loading={tableLoading}
        columns={tableColumns}
        dataSource={tableData}
        pagination={{
          total,
          pageSize,
          currentPage: page,
          showSizeChanger: true,
          onChange: handleTablePaginationChange,
        }}
        scroll={{ x: 'max-content' }}
      />
    </div>
  );
}

export default FieldsGoodsServiceList;